import { AnimationClip, Sprite, SpriteFrame, animation } from 'cc'
import { ResourceManager } from '../ResoucesManager/ResourceManager'
import { StateMachine } from './StateMachine'
import { ANIMATION_SPEED } from './EntityManager'

/**
 * 1. 需要知道 animation clip
 * 2. 需要播放动画的能力 animation
 */
export class State {
  animClip: AnimationClip
  uniqueNum: number = this.generateUniqueNumber()

  constructor(
    private fsm: StateMachine,
    private path: string,
    private wrapMode: AnimationClip.WrapMode = AnimationClip.WrapMode.Normal,
  ) {
    this.init()
  }

  generateUniqueNumber(): number {
    let milliseconds = Math.floor(Date.now())
    // console.log('milliseconds', milliseconds)
    return milliseconds
  }

  async init() {
    const inst = ResourceManager.getInstance(ResourceManager)

    const promises = inst.loadDirectory(this.path)
    this.fsm.waitingList.push(promises)
    const spriteFrames = await promises

    this.animClip = new AnimationClip()

    const track = new animation.ObjectTrack()
    track.path = new animation.TrackPath().toComponent(Sprite).toProperty('spriteFrame')

    const frames: Array<[number, SpriteFrame]> = spriteFrames.map((item, index) => [ANIMATION_SPEED * index, item])

    track.channel.curve.assignSorted(frames)

    // 最后将轨道添加到动画剪辑以应用
    this.animClip.addTrack(track)
    this.animClip.wrapMode = this.wrapMode

    let clipId = this.path + '-' + this.uniqueNum
    this.animClip.name = clipId

    let durationNum = frames.length * ANIMATION_SPEED
    this.animClip.duration = durationNum

    this.fsm.animComp.name = this.path
    this.fsm.animComp.defaultClip = this.animClip

    // console.log('State-init-this.fsm.animComp', this.fsm.animComp)
    // this.fsm.animComp.play()
  }

  run() {
    console.log('State-run-this.animComp', this.fsm.animComp)
    console.log('State-run-this.animClip', this.animClip.name)
    // let defaultClipId = this.fsm.animComp.clips[0].name
    // this.fsm.animComp.play(defaultClipId)
    this.fsm.animComp.defaultClip = this.animClip
    this.fsm.animComp.play()
  }
}
